/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
//<editor-fold  defaultstate="collapsed"  desc="0-Enunciado ">
/*
 * Se requeriere generar codigo de barra para cartones de bingo
 * guardar la imagenes
 */
//</editor-fold>
package my.work.gcb;

import system.Cronometro;
import system.Persistencia;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import my.work.gcb.Ibarcode;

/**
 *
 * @author UTPVirtual
 */
public class Main extends JFrame implements ActionListener, FocusListener {

    private Persistencia persistencia = new Persistencia();
    private JLabel etRinicial, etRfinal, etVisor;
    private JLabel etEini, etEfin, etcantlote;
    // Botones -> para iniciar el proceso de generacion de codigos de barras
    private JButton b_gsec, b_gbar;
    //Campos para los rangos inicial y final que generara los codigo de barras , 
    //cantidad de cartones por lote
    private JTextField jtini, jtfin, jtclote;
    Border border;
    JScrollPane sccgb;
    private JList jlgbc;
    // Clases
    private Numeracion ncgb;
    private Ibarcode barcode;
    private DefaultListModel lmcgb;
    private int ini, fin;

    // Configurando marca de agua sobre los campos
//public static const PROMPT_COLOR:Number = 0x999999;
    public Main() {
        super("Generador De Codigo Barra");
        setSize(440, 390);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        // dls = new FlowLayout();
        String appnsystem = System.getProperties().getProperty("os.name");
        System.out.println(appnsystem);
        setLayout(null);
    }

    private void crearGui() {
        border = LineBorder.createGrayLineBorder();
        //Creando etiquetas   
        etRinicial = new JLabel();
        etRfinal = new JLabel();
        etVisor = new JLabel();
        etEini = new JLabel();
        etEfin = new JLabel();
        etcantlote = new JLabel();
        // Creando lista 
        jlgbc = new JList();
        //Creando Botones 
        b_gsec = new JButton();
        b_gbar = new JButton();

        // Creando  Campos de Textos
        jtini = new JTextField();
        jtfin = new JTextField();
        jtclote = new JTextField();
// Creando los scroll q contendran las listas
        sccgb = new JScrollPane(jlgbc);
        //asignando texto
        etRinicial.setText("Intervalo Inicial:");
        etRfinal.setText("Intervalo Final:");
        etVisor.setText("Secuencias");
        etcantlote.setText("Cartones por lote:");
        jtini.setText("Inical");

        b_gsec.setText("Generar Secuencias");
        b_gbar.setText("Crear Barras");
        // asignando bordes
        etRinicial.setBorder(border);
        etRfinal.setBorder(border);
        etVisor.setBorder(border);
        etcantlote.setBorder(border);
        //

// etiquetas
        add(etRinicial);
        add(etRfinal);
        add(etVisor);
        add(etEini);
        add(etEfin);
        add(etcantlote);
        //Boton 
        add(b_gsec);
        add(b_gbar);
// Campos de textos
        add(jtini);
        add(jtfin);
        add(jtclote);
        // Scroll
        add(sccgb);
        // Evento de botones
        b_gsec.addActionListener(this);
        b_gbar.addActionListener(this);
        //Eventos de focus
        jtini.addFocusListener(this);
        jtfin.addFocusListener(this);

    }

    private void dimension() {
        //<editor-fold desc="3-Dimencionamiento">
        //Etiqueta de rango de cartones bingo 
        //                  (posicion(x , y ) , ancho , altura)
        etRinicial.setBounds(25, 10, 100, 25);
        etRfinal.setBounds(150, 10, 100, 25);
        etEini.setBounds(20, 50, 150, 25);
        etEfin.setBounds(142, 50, 150, 25);
        etVisor.setBounds(24, 130, 110, 20);
        etcantlote.setBounds(25, 80, 120, 25);
        //Campos de rango de  cartones de bingo 
        jtini.setBounds(24, 36, 110, 20);
        jtfin.setBounds(149, 36, 110, 20);
        jtclote.setBounds(24, 105, 124, 20);
        // scroll 
        sccgb.setBounds(24, 150, 110, 100);
        //boton
        b_gsec.setBounds(266, 36, 150, 20);
        b_gbar.setBounds(140, 150, 110, 20);
        //</editor-fold>
    }

    private static boolean isNumeric(String cadena) {
        try {
            Integer.parseInt(cadena);
            return true;
        } catch (NumberFormatException nfe) {
            return false;
        }
    }

    private boolean exrango(int inicio, int fin) throws SQLException, Exception {
        int ncarton = 0;
        String sql;
        //   sql = "INSERT INTO \"barcode\" (n_carton,n_serie,lote)    VALUES (" + c + ",'" + code + "', " + loteact + "  )";
        //  persistencia.executeUpdate(sql);
        boolean flag = true;
        sql = " Select *   From Barcode Where   n_carton=" + inicio;
        ResultSet rsts = persistencia.executeRsts(sql);
       if(rsts.next()) {
            ncarton = rsts.getInt("n_carton");
        }

        if (ncarton == inicio) {
            rsts.close();
            return true;
        }
        rsts.close();
        return false;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Main GCB = new Main();
        GCB.crearGui();
        GCB.dimension();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == b_gsec) {
            try {
                ini = Integer.parseInt(jtini.getText());
                fin = Integer.parseInt(jtfin.getText());
                if (ini > fin) {
                    fin = Integer.parseInt(jtini.getText());
                    ini = Integer.parseInt(jtfin.getText());
                }


               // if (ini <= fin) {
                    if (!exrango(ini, fin)) {
                        ncgb = new Numeracion(ini, fin);
                        lmcgb = ncgb.generar_rango();
                        jlgbc.setModel(lmcgb);
                    } else {
                        JOptionPane.showMessageDialog(null, "El rango ya existe", "About", JOptionPane.WARNING_MESSAGE);
                    }
             /*   } else {
                    JOptionPane.showMessageDialog(null, "El Numero Inicio deve de ser menor al del el final", "About", JOptionPane.WARNING_MESSAGE);
                }*/
            } catch (SQLException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            } catch (Exception ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        if (e.getSource() == b_gbar) {
            try {
                if (isNumeric(this.jtclote.getText())) {
                    Cronometro crom = new Cronometro(); //Intancio la clase
                    crom.start();
                    //ini = Integer.parseInt(jtini.getText());
                    int lote = Integer.parseInt(this.jtclote.getText());
                    barcode = new Ibarcode(lote, ini);
                    barcode.g_codebar(lmcgb);
                    //barcode.insert(lmcgb);
                    crom.terminar = true;
                } else {
                    JOptionPane.showMessageDialog(null, "Porfavor Introduzca El Lote", "About", JOptionPane.WARNING_MESSAGE);
                }
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }/*catch (Exc ex) {
             Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
             } catch (SQLException ex) {
             Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
             } catch (NamingException ex) {
             Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
             }*/ catch (Exception ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }


    }

    @Override
    public void focusGained(FocusEvent e) {
        if (e.getSource() == jtini) {
            if (!isNumeric(jtini.getText())) {
                jtini.setText("");
            }
        }
        if (e.getSource() == jtfin) {
            if (!isNumeric(etEfin.getText())) {
                etEfin.setText("");
            }
        }
    }

    @Override
    public void focusLost(FocusEvent e) {
        if (e.getSource() == jtini) {
            if (!isNumeric(jtini.getText())) {
                etEini.setText("ingresar un numero");
            } else {
                etEini.setText("");
            }

        }

        if (e.getSource() == jtfin) {
            if (!isNumeric(jtini.getText())) {
                etEfin.setText("ingresar un numero");
            } else {
                etEfin.setText("");
            }
        }
    }
}
